package com.academy.teacher;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import com.academy.querystapp.HomeActivity;
import com.academy.querystapp.R;
import com.academy.services.BaseService;
import com.academy.services.RequestMethod;
import com.academy.services.ResponseListener;
import com.academy.student.StudentForgetPassword;
import com.academy.student.QueryTabActivity;
import com.academy.student.StudentActivity;
import com.academy.util.AcademyUtility;

public class TeacherActivty extends Activity implements OnClickListener,ResponseListener
{
	Button btnRegistration,btnLogin;
	EditText edtMobileNo,edtPassword;
	Button btnForgetPassword;	
	
	
	
	String message, title;
	
	String strUserName,strPassword,sessionID;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_teacher);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		initializeViews();
		if(getIntent().hasExtra("sessionID"))
		{
			sessionID=getIntent().getExtras().getString("sessionID");
			System.out.println("sessionID --> "+sessionID);
			edtMobileNo.setText(sessionID);
		}
	}
	
	public void initializeViews()
	{
		edtMobileNo=(EditText) findViewById(R.id.edtMobileNo);
		edtPassword=(EditText) findViewById(R.id.edtPassword);
		btnLogin=(Button) findViewById(R.id.btnLogin);
		btnRegistration=(Button) findViewById(R.id.btnRegistration);
		btnForgetPassword=(Button) findViewById(R.id.btnForgetpassword);
		btnForgetPassword.setOnClickListener(this);
		btnLogin.setOnClickListener(this);
		btnRegistration.setOnClickListener(this);		
	}

	@Override
	public void onClick(View v) 
	{
		if(v==btnLogin)
		{
			strUserName=edtMobileNo.getText().toString().trim();
			strPassword=edtPassword.getText().toString().trim();
			
			if(strUserName.equals("")&& strPassword.equals(""))
			{
				
				Builder builder = new Builder(this);
				builder.setTitle("Login");
				builder.setMessage("Please Enter the Username and Password!");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
			else if(strUserName.equals(""))
			{
			
				Builder builder = new Builder(this);
				builder.setTitle("Login");
				builder.setMessage("Please Type Your Username!");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
			else if(strUserName.length()<4||strUserName.length()>4)
			{
				
				Builder builder = new Builder(this);
				builder.setTitle("Login");
				builder.setMessage("Enter your 4 digit Session ID !");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}else if(strPassword.equals(""))
			{
				
				Builder builder = new Builder(this);
				builder.setTitle("Login");
				builder.setMessage("Please Type Your password!");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}			
			else
			{				
				
				BaseService baseService = new BaseService(this,this,RequestMethod.GET);
				baseService.addParam(getString(R.string.userName_param), edtMobileNo.getText().toString());
				baseService.addParam(getString(R.string.userType_Param),"Teacher");
				//		    					
				baseService.execute(getString(R.string.loginTeacherURL));
		    				      						
			}
			
		}
		
		if(v==btnForgetPassword)
		{
			Intent ii=new Intent(this,TeacherForgetPassword.class);
			startActivity(ii);
		}
		
		if(v==btnRegistration)
		{
			Intent ii=new Intent(this,TeacherRegistration.class);
			startActivity(ii);
		}
	}

	public boolean chkWiFi()
	{
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if( ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI )
		{
			return true;			
		}
		else
		{			
			return false;			
		}
	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {

	    View v = getCurrentFocus();
	    boolean ret = super.dispatchTouchEvent(event);

	    if (v instanceof EditText) {
	        View w = getCurrentFocus();
	        int scrcoords[] = new int[2];
	        w.getLocationOnScreen(scrcoords);
	        float x = event.getRawX() + w.getLeft() - scrcoords[0];
	        float y = event.getRawY() + w.getTop() - scrcoords[1];

	        Log.d("Activity", "Touch event "+event.getRawX()+","+event.getRawY()+" "+x+","+y+" rect "+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords "+scrcoords[0]+","+scrcoords[1]);
	        if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) { 

	            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
	            imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
	        }
	    }
	return ret;
	}

	
//	public void onBackPressed() 
//	{
//		   Intent back=new Intent(getApplicationContext(),HomeActivity.class);
//		   startActivity(back);
//		   this.finish();
//	}
	
	private void parseResponse(String response)
	{
		if(response==null ||response.equals("null"))
		{
			System.out.println("Response ---> "+response);
				
			showAlert(null, "No Server Found!");
		}
		else
		{
			try 
			{ 
			
				JSONObject RootObject = new JSONObject(response);
				System.out.println("JSON Object==> "+RootObject.toString());
				JSONObject teacherObject = RootObject.getJSONObject("teacher");
				JSONObject teacherData=teacherObject.getJSONObject("QueryBeanData");
				String strStatus=teacherData.getString("status");
				System.out.println("teacherData="+teacherData);

				if(strStatus.equals("true"))
				{			
					AcademyUtility.setName(teacherData.getString("teacherName"));
					AcademyUtility.setCollegeName(teacherData.getString("college_Name"));
//					AcademyUtility.setQualification(teacherData.getString("qualification"));
					AcademyUtility.setEmailID(teacherData.getString("emailID"));
					AcademyUtility.setDesignation(teacherData.getString("designation"));
					
					AcademyUtility.setTeacherID(strUserName);
					System.out.println("password===>"+teacherData.getString("password"));
					if(strPassword.equals(teacherData.getString("password")))
					{
						Intent ii=new Intent(this,TeacherTabActivity.class);
						startActivity(ii);	
					}
					else
					{
						showAlert("Login", "Password Mismatch");
					}
					
					
//					showAlert(null, "Logged in");			
				}
				else if(strStatus.equals("false"))
				{
					String strError= teacherData.getString("errorDesc");
					showAlert(null, strError);
				}
			}
			catch (JSONException e) 
			{
				e.printStackTrace();
			} 
		}
	}
	
	
	public void showAlert(String Title,String Message)
	{
		Builder builder = new Builder(this);
		builder.setTitle(Title);
		builder.setMessage(Message);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int arg1)
			{	
//				Intent i=new Intent(StudentActivity.this,Homepage.class);
//				startActivity(i);
//				finish();						
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();	
	}

	@Override
	public void onServiceCompleted(String response, String requestURL) {
		parseResponse(response);
		
	}

	@Override
	public void onServiceFailed(String exception, String requestURL) {
		// TODO Auto-generated method stub
		
	}
	
	
	public Boolean TeacherLoginTestCase(String strUserName,String StrPassword)
	{
		Boolean validate=false;
		
		if(strUserName!=null && StrPassword!=null)
		{
			validate=true;
			System.out.println("Username & Password not null");
		}
		else
		{
			validate=false;
			System.out.println("Username or Password null");
		}
		
		return validate;
		
	}

}
